package com.wenye.interceptors;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wenye.Util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取令牌
        String token = request.getHeader("token");
        Cookie[] cookies = request.getCookies();

        for(Cookie a:cookies) {
            System.out.println(a.getName());
            if(a.getName().equals("token")){
                System.out.println("TOKEN==="+token);
                token=a.getValue();
            }
        }

        Map<String, Object> map = new HashMap<>();

        try {
            JWTUtil.Verify(token);
            // 验证通过，不予拦截
            return true;
        }catch(TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
        }catch(Exception e){
            e.printStackTrace();
            map.put("msg","token无效");
        }

        map.put("state",false);

        response.sendRedirect("http://localhost:8000/user/login?"+request.getRequestURL());
        return false;
    }
}
